<template>
  <div class="min-h-screen flex items-center justify-center relative">
    <div class="aurora-background">
    </div>
    <div class="w-full max-w-md relative z-10">
      <!-- 忘记密码卡片 -->
      <div class="bg-white rounded-2xl shadow-2xl p-8 mx-4">
        <!-- Logo 和标题 -->
        <div class="text-center mb-8">
          <div class="flex justify-center mb-4">
            <img src="/logo.svg" alt="CodeWin" class="w-16 h-16" />
          </div>
          <h1 class="text-2xl font-bold text-gray-800 mb-2">CodeWin</h1>
          <p class="text-gray-500 text-sm">重置您的密码</p>
        </div>

        <!-- 重置密码表单 -->
        <form @submit.prevent="handleResetPassword" class="space-y-6">
          <!-- 用户名输入 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">
              用户名
            </label>
            <a-input
              v-model:value="resetForm.username"
              placeholder="请输入您的用户名"
              size="large"
              class="w-full"
            >
              <template #prefix>
                <User :size="16" />
              </template>
            </a-input>
          </div>

          <!-- 邮箱输入 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">
              邮箱
            </label>
            <a-input
              v-model:value="resetForm.email"
              type="email"
              placeholder="请输入您的邮箱"
              size="large"
              class="w-full"
            >
              <template #prefix>
                <Mail :size="16" />
              </template>
            </a-input>
          </div>

          <!-- 验证码输入 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">
              邮箱验证码
            </label>
            <div class="flex space-x-2">
              <a-input
                v-model:value="resetForm.code"
                placeholder="请输入验证码"
                size="large"
                class="flex-1"
              >
                <template #prefix>
                  <Shield :size="16" />
                </template>
              </a-input>
              <a-button
                size="large"
                :loading="sendingCode"
                :disabled="!resetForm.email || countdown > 0"
                @click="sendVerificationCode"
                class="px-4"
              >
                {{ countdown > 0 ? `${countdown}s` : '发送验证码' }}
              </a-button>
            </div>
          </div>

          <!-- 新密码输入 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">
              新密码
            </label>
            <a-input-password
              v-model:value="resetForm.newPassword"
              placeholder="请输入新密码"
              size="large"
              class="w-full"
            >
              <template #prefix>
                <Lock :size="16" />
              </template>
            </a-input-password>
          </div>

          <!-- 确认新密码输入 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">
              确认新密码
            </label>
            <a-input-password
              v-model:value="resetForm.confirmPassword"
              placeholder="请再次输入新密码"
              size="large"
              class="w-full"
            >
              <template #prefix>
                <Lock :size="16" />
              </template>
            </a-input-password>
          </div>

          <!-- 重置密码按钮 -->
          <a-button
            type="primary"
            html-type="submit"
            size="large"
            :loading="loading"
            class="w-full h-12 text-base font-medium bg-gradient-to-r from-violet-500 to-purple-600 border-none hover:from-violet-600 hover:to-purple-700"
          >
            重置密码
          </a-button>
        </form>

        <!-- 分割线 -->
        <div class="mt-6 mb-6">
          <div class="relative">
            <div class="absolute inset-0 flex items-center">
              <div class="w-full border-t border-gray-300"></div>
            </div>
          </div>
        </div>

        
        <!-- 注册链接 -->
        <div class="mt-2 text-center">
          <span class="text-sm text-gray-600">
            还没有账户？
            <router-link to="/register" class="font-medium text-violet-600 hover:text-violet-500">
              立即注册
            </router-link>
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { Mail, Lock, User, Shield } from 'lucide-vue-next'
import { Codewin } from '@/api/generated/Codewin'
import type { ResetPasswordRequest } from '@/api/generated/data-contracts'

const router = useRouter()
const loading = ref(false)
const sendingCode = ref(false)
const countdown = ref(0)

// 创建API实例
const api = new Codewin({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api'
})

const resetForm = reactive({
  username: '',
  email: '',
  code: '',
  newPassword: '',
  confirmPassword: ''
})

// 发送验证码
const sendVerificationCode = async () => {
  if (!resetForm.email) {
    message.error('请先输入邮箱地址')
    return
  }

  // 简单的邮箱格式验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(resetForm.email)) {
    message.error('请输入正确的邮箱格式')
    return
  }

  sendingCode.value = true
  
  try {
    await api.sendCode({ email: resetForm.email })
    message.success('验证码已发送到您的邮箱')
    
    // 开始倒计时
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error: any) {
    console.error('发送验证码失败:', error)
    message.error(error?.response?.data?.message || '发送验证码失败，请稍后重试')
  } finally {
    sendingCode.value = false
  }
}

// 处理重置密码
const handleResetPassword = async () => {
  // 表单验证
  if (!resetForm.username || !resetForm.email || !resetForm.code || !resetForm.newPassword || !resetForm.confirmPassword) {
    message.error('请填写完整的重置信息')
    return
  }

  if (resetForm.newPassword !== resetForm.confirmPassword) {
    message.error('两次输入的密码不一致')
    return
  }

  if (resetForm.newPassword.length < 6) {
    message.error('密码长度不能少于6位')
    return
  }

  loading.value = true
  
  try {
    // 构造重置密码请求参数
    const resetData: ResetPasswordRequest = {
      username: resetForm.username,
      email: resetForm.email,
      code: resetForm.code,
      newPassword: resetForm.newPassword
    }

    const response = await api.resetPassword(resetData)
    
    if (response.data?.data) {
      message.success('密码重置成功！请使用新密码登录')
      router.push('/login')
    } else {
      message.error(response.data?.message || '密码重置失败')
    }
  } catch (error: any) {
    console.error('密码重置失败:', error)
    message.error(error?.response?.data?.message || '密码重置失败，请稍后重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
/* 自定义样式 */
.ant-input-affix-wrapper {
  border-radius: 8px;
}

.ant-btn {
  border-radius: 8px;
}
</style>